﻿Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.IO

<ServiceContract(Namespace:="")>
<SilverLightFaultBehavior>
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)>
Public Class Service1

    Shared listofmembers As New List(Of Users)

    <OperationContract()>
    Public Function SubScribe(ByVal AppId As String, ByVal UserId As String, ByVal ChannelUri As String) As ExecptionsClass
        Try
            Dim member = New Users With {.Appid = AppId, .UserId = UserId, .Channel = ChannelUri}
            listofmembers.Add(member)
            Me.AddUserToXmlFile(AppId, UserId, ChannelUri)
            Return New ExecptionsClass With {.HasError = False, .User = member}
        Catch ex As Exception
            Return New ExecptionsClass With {.HasError = True, .User = New Users With {.Appid = AppId, .UserId = UserId}, .Message = ex.Message.ToString, .Source = ex.Source.ToString, .TargetSite = ex.TargetSite.ToString}
        End Try
    End Function


    <OperationContract()>
    Public Function UnSubScribe(ByVal appId As String, ByVal userid As String) As ExecptionsClass
        Try
            Dim a = From b In listofmembers
                    Where b.Appid = appId And b.UserId = userid
                    Select b

            If a(0) IsNot Nothing Then
                listofmembers.Remove(a(0))
            End If
            RemoveUserFromXML(appId, userid)
            Return New ExecptionsClass With {.HasError = False, .User = a(0)}
        Catch ex As Exception
            Return New ExecptionsClass With {.HasError = True, .User = New Users With {.Appid = appId, .UserId = userid}, .Message = ex.Message.ToString, .Source = ex.Source.ToString, .TargetSite = ex.TargetSite.ToString}
        End Try

    End Function
    <OperationContract>
    Public Function UpdateSubscription(ByVal appid As String, ByVal userid As String, ByVal channeluri As String) As ExecptionsClass
        Try
            Dim a = From b In listofmembers
                    Where b.Appid = appid And b.UserId = userid
                    Select b

            If a(0) IsNot Nothing Then
                a(0).Channel = channeluri
            End If
            RemoveUserFromXML(appid, userid)
            AddUserToXmlFile(appid, userid, channeluri)
            Return New ExecptionsClass With {.HasError = False, .User = a(0)}
        Catch ex As Exception
            Return New ExecptionsClass With {.HasError = True, .User = New Users With {.Appid = appid, .UserId = userid}, .Message = ex.Message.ToString, .Source = ex.Source.ToString, .TargetSite = ex.TargetSite.ToString}
        End Try
    End Function
    <OperationContract()>
    Public Function GetMembers() As List(Of Users)
        Return listofmembers
    End Function
    ' Add more operations here and mark them with <OperationContract()>


    Private Function MyFile() As String
        'Return System.IO.Path.Combine("../ClientBin", "users.txt")
        Return Path.GetFullPath(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "users.xml"))
    End Function

    Function CreateXML() As XDocument
        If System.IO.File.Exists(MyFile) Then
            Return XDocument.Load(MyFile)
        Else
            Dim xdoc As New XDocument
            Dim Root As XElement = <Users>

                                   </Users>
            xdoc.Add(Root)
            xdoc.Save(MyFile)
            Return xdoc
        End If
    End Function

    Private Sub AddUserToXmlFile(ByVal Appid As String, ByVal UserId As String, ByVal Channel As String)
        Dim xdoc = CreateXML()

        Dim elements = From b In xdoc.Root.Elements
                       Where b.<appid>.Value = Appid And b.<userid>.Value = UserId
                       Select b

        If elements(0) Is Nothing Then


            Dim newElement As XElement = <User>
                                             <appid><%= Appid %></appid>
                                             <userid><%= UserId %></userid>
                                             <channel><%= Channel %></channel>
                                         </User>
            xdoc.Root.Add(newElement)
            xdoc.Save(MyFile)
        Else
        End If

    End Sub

    Private Sub RemoveUserFromXML(ByVal appid As String, ByVal userid As String)
        Dim xdoc = CreateXML()

        Dim user = From a In xdoc.Root.Elements
                   Where a.<appid>.Value = appid And a.<userid>.Value = userid
                   Select a

        Me.LogEvents("in RemoveUserFromXML: " & user(0).<appid>.Value.ToString)

        If user(0) IsNot Nothing Then
            user(0).Remove()
            xdoc.Save(MyFile)
        End If
    End Sub

    Private Function ReadAllUsersFromXMLFile() As List(Of Users)
        Dim retlist As New List(Of Users)
        Dim xdoc = CreateXML()
        For Each a In xdoc.Root.Elements
            Dim nuser As New Users
            With nuser
                .Appid = a.<appid>.Value.ToString
                .UserId = a.<userid>.Value.ToString
                .Channel = a.<channel>.Value.ToString
            End With
            retlist.Add(nuser)
        Next
        Return retlist
    End Function

    Private Function ReadAllUsersFromXMLFile(ByVal xdocs As XDocument) As List(Of Users)
        Dim retlist As New List(Of Users)
        Dim xdoc = xdocs
        For Each a In xdoc.Root.Elements
            Dim nuser As New Users
            With nuser
                .Appid = a.<appid>.Value.ToString
                .UserId = a.<userid>.Value.ToString
                .Channel = a.<channel>.Value.ToString
            End With
            retlist.Add(nuser)
        Next
        Return retlist
    End Function

    Public Sub New()
        LogEvents("Start with New()")
        listofmembers = ReadAllUsersFromXMLFile()
    End Sub

    Private Sub LogEvents(ByVal strings As String)
        Dim logfile = Path.GetFullPath(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "logfile.txt"))
        Using a As System.IO.StreamWriter = New System.IO.StreamWriter(logfile, True)
            a.WriteLine(strings)
        End Using
    End Sub

End Class

Public Class Users
    Property Appid As String
    Property UserId As String
    Property Channel As String
End Class

Public Class ExecptionsClass
    Property Message As String
    Property Source As String
    Property TargetSite As String
    Property HasError As Boolean
    Property User As Users
End Class
